<template>
    <div>
        <el-dialog
            title="游戏兑换"
            :visible.sync="GameChangeDialogVisible"
            width="480px"
            center
            v-dialogDrag
            :close-on-click-modal="false"
            @close="resetFormLabelAlign('gameForm')"
            :append-to-body="true"
            class="gameChange"
        >
            <div>
                <h3>您正在进行：{{ gameName }} 的游戏兑换服务</h3>
                <p class="edu">
                    您剩余可用{{ typeTitle }}：
                    <span>{{ balance }}</span>
                </p>
                <el-form label-position="top" status-icon label-width="80px" :model="gameForm" ref="gameForm" :rules="rules">
                    <el-form-item label="兑换方式" prop="type" :rules="{ required: true, message: '请选择兑换方式', trigger: 'change' }" style="margin-top: 15px">
                        <el-select v-model="gameForm.type" placeholder="请选择兑换方式" :popper-append-to-body="false" @focus="setMinWidth" @change="typeChange">
                            <el-option v-for="(item, index) in typeList" :key="index" :label="item.type" :value="item.type" :style="{ 'min-width': minWidth + 'px' }"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="游戏分区" prop="regional" :rules="{ required: true, message: '请选择游戏分区', trigger: 'change' }" style="margin-top: 15px">
                        <el-select v-model="gameForm.regional" placeholder="请选择游戏分区" :popper-append-to-body="false" @focus="setMinWidth">
                            <el-option v-for="(item, index) in regional" :key="index" :label="item.title" :value="item.id" :style="{ 'min-width': minWidth + 'px' }"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="游戏账号" prop="gameAccount">
                        <el-input v-model="gameForm.gameAccount" placeholder="请输入正确的游戏账号" onkeyup="this.value=this.value.replace(/[ ]/g,'')"></el-input>
                    </el-form-item>
                    <el-form-item :label="gameName + '平台币兑换数量'" prop="topUp">
                        <el-input v-model.number="gameForm.topUp" :placeholder="'请输入' + gameName + '平台币兑换数量或选择兑换数量'" @keyup.enter.native="gameChangeAll('gameForm')"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div class="money">
                <el-radio-group v-model="money" size="mini" v-for="(item, index) in label" :key="index" @change="postInput(item.cash)">
                    <el-radio-button plain size="mini" :label="item.cash"></el-radio-button>
                </el-radio-group>
            </div>
            <div class="tishi">
                <h5>提示</h5>
                <p v-html="exTipText"></p>
            </div>
            <div style="width: 480px; text-align: center">
                <el-button type="primary" @click="gameChangeAll('gameForm')" :loading="loading" :disabled="disabled" class="button_btn widthHeight">
                    <span v-if="!loading">确定</span>
                    <span v-else>兑换中...</span>
                </el-button>
                <el-button @click="GameChangeDialogVisible = false" class="button_close widthHeight">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="兑换" :visible.sync="coinDialogVisible" width="330px" :modal-append-to-body="true" :append-to-body="true" center @close="wxbd()" class="wx">
            <p class="anquan">为了给你提供更好的服务</p>
            <h4 class="mima">请微信扫一扫验证二维码</h4>
            <img style="width: 200px; margin-left: 40px; min-height: 200px" :src="image_Src ? image_Src : ''" alt="" />
            <el-button style="margin-top: 48px" type="primary" @click="coinDialogVisible = false" class="button_btn">确定</el-button>
        </el-dialog>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { cashBenefitss, exchangeOrderStatuss, getpkScoreBalances, exTipTexts, getexchanges, pkCoins, conversionCodes, scoreCoins, versionLists, postGameCollects } from '@/api/url'
export default {
  created () {
  },
  data () {
    // 兑换数量验证
    var checktopUp = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入兑换数量'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value > this.balance) {
            callback(new Error('兑换数量不能大于剩余可兑换数量'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    // 游戏账号验证
    const checkGameAccount = (rule, value, callback) => {
      const sfz = /^[A-Za-z0-9\\d]+$/
      if (!value) {
        return callback(new Error('请输入正确的游戏账号'));
      }
      if (value === '' || sfz.test(value) === false) {
        callback(new Error('请输入正确游戏账号,不支持特殊字符！'))
      } else {
        callback()
      }
    }
    return {
      disabled: false,
      minWidth: '',
      coinDialogVisible: false,// 兑换扫码弹窗
      image_Src: '',// 兑换微信二维码
      sceneStr: '',// 二维码轮询唯一标识
      token: '',
      game_id: '', // 游戏id
      loading: false,
      regional: '', // 分区列表
      gameName: '', // 兑换当前的游戏名称
      typeList: [{ type: '平台币' }, { type: '积分' }, { type: 'pk币' },], // 兑换种类
      GameChangeDialogVisible: false, // 兑换弹窗默认关闭
      gameForm: {// 平台币
        type: '',
        regional: '',
        gameAccount: '',
        topUp: ''
      },
      money: '', // 循环金额
      typeTitle: '', // 循环金额
      moneyType: '', // 循环金额
      label: ['50', '100', '200', '300', '500', '1000'],
      requestId: '', // 请求唯一标识，兑换订单返回
      startTime: 0, // 兑换初始开始请求时间
      timer: null,
      codeStartTime: 0, // 二维码初始开始请求时间
      codeTimer: null,
      balance: 0, // 当前登录用户的币
      exTipText: '', // 提示富文本
      collect: 'true',//游戏收藏
      rules: {
        gameAccount: [
          { trigger: 'blur', validator: checkGameAccount, required: true },
          { min: 2, max: 20, message: '游戏账号在2~20位之间的英文或数字', trigger: 'blur' },
        ],
        topUp: [{ validator: checktopUp, trigger: 'blur', required: true }],
      }
    }
  },
  mounted () {
    this.$EventBus.$off("change_data")
    this.$EventBus.$on('change_data', data => {
      this.game_id = data
      this.send_request()
    })
  },
  methods: {
    // 游戏收藏
    async postGameCollects () {
      try {
        const res = await postGameCollects({ versionId: this.game_id, collect: this.collect })
        if (res.data.code === 200) {
          // this.$message({ message: '恭喜你，游戏收藏成功', type: 'success', center: true })
          console.log('兑换后收藏了游戏');
        } else {
          console.log(res.data.msg);
          // this.$message({ message: res.data.msg, type: 'warning', center: true })
        }
      } catch (err) {
        console.log(err)
      }
    },
    gameChangeAll (item) {
      this.loading = true
      this.disabled = true
      this.$refs[item].validate((valid) => {
        if (valid) {
          if (this.gameForm.type === '平台币') {
            this.submitForm()//平台币游戏兑换请求
          } else if (this.gameForm.type === '积分') {
            this.scoretopUpsubmitForm()//积分游戏兑换请求
          } else {
            this.pkCoinsubmitForm()//PK币游戏兑换请求
          }
        } else {
          console.log('error submit!!')
          this.loading = false
          this.disabled = false
          return false
        }
      })
    },
    // 发送平台币游戏兑换请求
    submitForm () {
      try {
        cashBenefitss({ gameId: this.game_id, merGameTemplateId: this.gameForm.regional, gameAccount: this.gameForm.gameAccount, type: this.gameForm.type, credit: parseInt(this.gameForm.topUp) }).then((res) => {
          // console.log(res)
          if (res.data.code === 200) {
            this.requestId = res.data.requestId
            this.handlerData()
          } else {
            this.$message({ message: res.data.msg, type: 'error', center: true })
            this.loading = false
            this.disabled = false
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 发送PK币游戏兑换请求
    pkCoinsubmitForm (formName) {
      try {
        pkCoins({ gameId: this.game_id, merGameTemplateId: this.gameForm.regional, gameAccount: this.gameForm.gameAccount, type: this.gameForm.type, credit: parseInt(this.gameForm.topUp) }).then((res) => {
          if (res.data.code === 200 && res.data.pkCodes === true) {
            this.requestId = res.data.data.requestId
            this.sceneStr = res.data.data.scene_str
            this.image_Src = 'data:image/gif;base64,' + res.data.data.image_src
            this.coinDialogVisible = true
            this.codeHandlerData()
          } else if (res.data.code === 200 && res.data.pkCodes === false) {
            this.requestId = res.data.requestId
            this.handlerData()
          } else {
            this.$message({ message: res.data.msg, type: 'error', center: true })
            this.loading = false
            this.disabled = false
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 发送积分游戏兑换请求
    scoretopUpsubmitForm (formName) {
      try {
        // this.type = '积分'
        scoreCoins({ gameId: this.game_id, merGameTemplateId: this.gameForm.regional, gameAccount: this.gameForm.gameAccount, type: this.gameForm.type, credit: parseInt(this.gameForm.topUp) }).then((res) => {
          // console.log(res)
          if (res.data.code === 200 && res.data.pkCodes === true) {
            this.requestId = res.data.data.requestId
            this.sceneStr = res.data.data.scene_str
            this.image_Src = 'data:image/gif;base64,' + res.data.data.image_src
            this.coinDialogVisible = true
            this.codeHandlerData()
          } else if (res.data.code === 200 && res.data.pkCodes === false) {
            this.requestId = res.data.requestId
            this.handlerData()
          } else {
            this.$message({ message: res.data.msg, type: 'error', center: true })
            this.loading = false
            this.disabled = false
          }
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 兑换方式选中的值
    typeChange () {
      this.typeTitle = this.gameForm.type;
      if (this.gameForm.type === '平台币') {
        this.balance = this.moneyType.balance
      } else if (this.gameForm.type === '积分') { this.balance = this.moneyType.score } else {
        this.balance = this.moneyType.pkCoin
      }
    },
    // 关闭微信绑定弹窗时清除扫码状态(轮询)的定时器
    wxbd () {
      clearTimeout(this.codeTimer)
      this.loading = false
      this.disabled = false
    },
    // 开始准备兑换轮询
    handlerData () {
      this.startTime = new Date().getTime() // 获取触发轮询时的时间
      this.inquireData() // 调用轮询接口,开始进行轮询
    },
    inquireData () {
      const reload = () => {
        clearTimeout(this.timer) // 清除定时器
        // 超过10秒则停止轮询
        if (new Date().getTime() - this.startTime > 10000) {
          clearTimeout(this.timer)
          this.$message({ message: '兑换超时,请再试一次', type: 'error', center: true })
          this.$EventBus.$emit('change_balance', 1)
          this.loading = false
          this.disabled = false
          this.postGameCollects()
          return
        }
        // 2s一次, 轮询中
        this.timer = setTimeout(() => {
          this.inquireData() // 调用轮询
        }, 2000)
      }
      exchangeOrderStatuss({ requestId: this.requestId })
        .then(res => {
          // console.log(res)
          if (res.data.code === 200) {
            // 需要查询的接口返回成功了,做相应的处理
            this.$message({ message: '恭喜你，兑换成功', type: 'success', center: true })
            setTimeout(() => {
              this.GameChangeDialogVisible = false// 三秒后关闭弹窗
              this.$EventBus.$emit('change_balance', 1)
              clearTimeout(this.timer)
              this.loading = false
              this.disabled = false
              this.postGameCollects()
            }, 3000)
          } else {
            if (res.data.lua) {
              this.$message({ message: '脚本错误', type: 'error', center: true })
              // console.log(res.data.msg)
              setTimeout(() => {
                this.GameChangeDialogVisible = false// 三秒后关闭弹窗
                this.$EventBus.$emit('change_balance', 1)
                clearTimeout(this.timer)
                this.loading = false
                this.disabled = false
                this.postGameCollects()
              }, 3000)
              console.log(res.data.lua, 'lua');
            } else if (res.data.error) {
              this.$message({ message: res.data.msg, type: 'error', center: true })
              setTimeout(() => {
                this.GameChangeDialogVisible = false// 三秒后关闭弹窗
                this.$EventBus.$emit('change_balance', 1)
                clearTimeout(this.timer)
                this.loading = false
                this.disabled = false
                this.postGameCollects()
              }, 3000)
              console.log(res.data.error, 'error');
            } else {
              // 没成功,调用轮询
              reload()
            }
          }
        })
        .catch(err => {
          // 请求错误,也继续轮询
          console.log(err)
          reload()
        })
    },
    // 开始准备二维码轮询
    codeHandlerData () {
      this.codeStartTime = new Date().getTime() // 获取触发轮询时的时间
      this.codeInquireData() // 调用轮询接口,开始进行轮询
    },
    codeInquireData () {
      const codeReload = () => {
        clearTimeout(this.codeTimer) // 清除定时器
        if (new Date().getTime() - this.codeStartTime > 30000) {
          clearTimeout(this.codeTimer)
          this.coinDialogVisible = false
          this.loading = false
          this.disabled = false
          return
        }
        // 2s一次, 轮询中
        this.codeTimer = setTimeout(() => {
          this.codeInquireData() // 调用轮询
        }, 2000)
      }
      conversionCodes({ sceneStr: this.sceneStr })
        .then(res => {
          if (res.data.code === 200) {
            // 需要查询的接口返回成功了,做相应的处理
            clearTimeout(this.codeTimer)
            this.coinDialogVisible = false
            this.handlerData()
          } else if (res.data.code === 555) {
            // 没成功,调用轮询
            codeReload()
          } else {
            clearTimeout(this.codeTimer)
            this.$message({ message: res.data.msg, type: 'error', center: true })
            this.coinDialogVisible = false
            this.loading = false
            this.disabled = false
          }
        })
        .catch(err => {
          // 请求错误,也继续轮询
          console.log(err)
          codeReload()
        })
    },
    // 点击关闭时清空input账户的的数据，关闭轮询
    resetFormLabelAlign (gameForm) {
      this.balance = 0
      this.money = ''
      this.typeTitle = ''
      this.$refs[gameForm].resetFields()
      clearTimeout(this.timer)
      this.loading = false
      this.disabled = false
    },
    // 点击发送请求
    send_request () {
      this.exTipTexts()
      this.versionLists()
      this.getpkScoreBalances()
      this.getexchanges().then(() => { this.GameChangeDialogVisible = true })
    },
    // 循环后点击对应的金额赋值给input
    postInput (val) {
      this.gameForm.topUp = Number(val)
    },
    // 获取当前登录用户的积分，平台币，PK币
    async getpkScoreBalances () {
      try {
        const res = await getpkScoreBalances()
        // console.log(res)
        if (res.data.code === 200) {
          this.moneyType = res.data.data
        } else if (res.data.code === 401) {
          this.$store.commit('setUser', {}) // 把本地的token清空
          this.$store.commit('user_xx', {}) // 把本地的token清空
          setTimeout(() => {
            this.$router.push('/')// 三秒后回到首页
          }, 3000)
        } else {
          console.log(res.data.msg)
          // this.$message({ message: res.data.msg, type: 'warning', center: true })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 兑换提示文本
    async exTipTexts () {
      try {
        const res = await exTipTexts()
        // console.log(res)
        if (res.data.code === 200) {
          this.exTipText = res.data.data
        } else {
          console.log(res.data.msg)
          // this.$message({ message: res.data.msg, type: 'warning', center: true })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取兑换金额
    async getexchanges () {
      try {
        const res = await getexchanges()
        // console.log(res, '获取兑换金额')
        if (res.data.code === 200) {
          const array = res.data.data
          const array1 = JSON.parse(array)
          this.label = array1
          // console.log(this.label)
        } else {
          console.log(res.data.msg)
          // this.$message({ message: res.data.msg, type: 'warning', center: true })
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 根据游戏id获取分区列表
    async versionLists () {
      try {
        const res = await versionLists(this.game_id)
        // console.log(res)
        if (res.data.code === 200) {
          this.regional = res.data.data
          this.gameName = res.data.gameName
        } else {
          console.log(res.data.msg)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 无数据的情况下，给请选择提示设置最小宽度
    setMinWidth (val) {
      let domEmpty = document.getElementsByClassName('el-select-dropdown__empty')
      if (domEmpty.length > 0) {
        domEmpty[0].style['min-width'] = val.srcElement.clientWidth + -2 + 'px'
      }
      this.minWidth = val.srcElement.clientWidth
    },
  },
  beforeDestroy () {
    clearTimeout(this.timer)
    this.$EventBus.$off("change_balance")
  },
  computed: { ...mapState(['user_mes', 'user']) },
  watch: {},
  filters: {},
  components: {}
}
</script>

<style scoped lang='less'>
/deep/ .el-dialog__body {
    height: 100% !important;
    padding: 20px !important;
    background: url('@/assets/dialogImg/VoucherCenterBG.png');
}
.widthHeight {
    width: 90px !important;
    height: 38px !important;
    margin-top: 20px;
}
.anquan {
    font-size: 11px;
    font-weight: 400;
    color: #979797 !important;
    letter-spacing: 0.33px;
}
.mima {
    font-size: 14px;
    font-weight: 500;
    color: #222223;
    letter-spacing: 0.42px;
    margin-bottom: 20px;
}
.gameChange {
    h3 {
        font-size: 15px;
        font-weight: 400;
        color: #f1e4c8;
        letter-spacing: 0.6px;
    }
    .edu {
        font-size: 14px;
        font-weight: 600;
        color: #f1e4c8;
        line-height: 25px;
        span {
            font-size: 16px;
            text-align: left;
            color: #ffb331;
            line-height: 25px;
        }
    }
    /deep/.el-dialog__title {
        font-size: 18px;
        font-weight: 400;
        color: #333333;
        letter-spacing: 0.54px;
    }
    /deep/.el-form-item {
        margin-bottom: 15px;
    }
    .money {
        /deep/.el-radio-button__inner {
            border-radius: 20px !important;
            border: 1px solid #ffb331;
            color: #ffb331;
            width: 60px;
            text-align: center;
            margin-bottom: 10px;
            margin-right: 10px;
            background: transparent;
            &:hover {
                color: #020102;
                background: #ffb331;
            }
        }
        /deep/.el-radio-button__orig-radio:checked + .el-radio-button__inner {
            border: 1px solid #ffb331;
            border-radius: 20px;
            box-shadow: 0px 0 0 0 #fff;
            color: #020102;
            background: #ffb331;
        }
    }
    .tishi {
        padding: 10px;
        background: transparent;
        border-radius: 4px;
        h5 {
            font-size: 12px;
            font-weight: 400;
            text-align: left;
            color: #dddddd;
            line-height: 20px;
            letter-spacing: 0.12px;
        }
        p {
            font-size: 12px;
            font-weight: 400;
            text-align: left;
            color: #979797;
            line-height: 20px;
            letter-spacing: 0.12px;
        }
    }
}
.el-select {
    display: block;
}
/deep/.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
    display: none;
}
/deep/.el-form-item__label {
    line-height: 0;
    padding: 0;
    color: #f1e4c8;
}
/deep/.el-form-item__error {
    padding-top: 0;
}
/deep/.el-input__inner {
    color: #ffb331;
}
/deep/.el-input__inner {
    color: #ffb331;
}
/deep/input::-webkit-input-placeholder {
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    text-align: left;
    color: #978152;
    font-family: '微软雅黑';
}
/deep/.el-select .el-input .el-select__caret {
    color: #ffb331;
}
</style>
